from sqlalchemy.orm import Session
import json
from typing import List
from app.entity import SysDept
from app.schema import DeptData
from utils.request import PageInfo
from utils.tree import TreeUtil

class DeptModel:
    """
    菜单管理模块数据库操作层
    """
    @classmethod
    def get_select_options(cls, db: Session):
        opts = db.query(SysDept).filter(SysDept.status==0).all()
        
        return opts

    @classmethod
    def insert(cls, db: Session, data: DeptData):
        db_post = SysDept(**data.dict())
        db.add(db_post)
        db.commit()
        return True
    

    @classmethod
    def edit(cls, db: Session, post: dict):
        db.query(SysDept).filter(SysDept.dept_id == post.get('dept_id')).update(post)
        db.commit()

    @classmethod
    def delete(cls, db: Session, ids: List[int]):
        db.query(SysDept).filter(SysDept.dept_id.in_(ids)).delete()
        db.commit()

    @classmethod
    def get_by_id(cls, db: Session, id: int):
        return db.query(SysDept).filter(SysDept.dept_id==id).first()
        

    @classmethod
    def get_page(cls, db: Session, where:dict, page: PageInfo ):
        total = db.query(SysDept).filter_by(**where).count()
        rows  = db.query(SysDept).filter_by(**where).offset((page.page-1)*page.limit).limit(page.limit).all()
        
        return total, rows
        
    @classmethod
    def get_dept_list(cls, db: Session, where):
        
        if where.get('dept_name', None)!=None:
            rows  = db.query(SysDept).filter(SysDept.dept_name==where['dept_name']).order_by(SysDept.dept_code).all()
            return rows
        else:
            rows  = db.query(SysDept).order_by(SysDept.dept_code).all()
            rows = [ v.__dict__ for v in rows ]
            return TreeUtil.build_tree_nodes(rows, 'dept_id', 'parent_id')